/* global window */
import React from 'react'
import classnames from 'classnames'
import { Input, Tooltip, Icon } from 'antd'
import lodash from 'lodash'
import config from './config'
import request from './request'
import { color } from './theme'
import { days } from './seletLocalData'

// 连字符转驼峰
String.prototype.hyphenToHump = function () {
  return this.replace(/-(\w)/g, (...args) => {
    return args[1].toUpperCase()
  })
}

// 驼峰转连字符
String.prototype.humpToHyphen = function () {
  return this.replace(/([A-Z])/g, '-$1').toLowerCase()
}

// 日期格式化
Date.prototype.format = function (format) {
  const o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'H+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds(),
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, `${this.getFullYear()}`.substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : (`00${o[k]}`).substr(`${o[k]}`.length))
    }
  }
  return format
}


/**
 * @param   {String}
 * @return  {String}
 */

const queryURL = (name) => {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
  let r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}

/**
 * 数组内查询
 * @param   {array}      array
 * @param   {String}    id
 * @param   {String}    keyAlias
 * @return  {Array}
 */
const queryArray = (array, key, keyAlias = 'key') => {
  if (!(array instanceof Array)) {
    return null
  }
  const item = array.filter(_ => _[keyAlias] === key)
  if (item.length) {
    return item[0]
  }
  return null
}

/**
 * 数组格式转树状结构
 * @param   {array}     array
 * @param   {String}    id
 * @param   {String}    pid
 * @param   {String}    children
 * @return  {Array}
 */
const arrayToTree = (array, id = 'id', pid = 'pid', children = 'children') => {
  let data = lodash.cloneDeep(array)
  let result = []
  let hash = {}
  data.forEach((item, index) => {
    hash[data[index][id]] = data[index]
  })

  data.forEach((item) => {
    let hashVP = hash[item[pid]]
    if (hashVP) {
      !hashVP[children] && (hashVP[children] = [])
      hashVP[children].push(item)
    } else {
      result.push(item)
    }
  })
  return result
}


const personDataField = (personType) => {
  let res = {}
  switch (personType) {
    case 'signPerson':
      res.revField = 'signatory'
      res.sendField = ''
      break
    case 'entityDirectorPerson':
      break
    default:
      break
  }
  return res
}
function converDate (date) { // 转换年月日
  if (date) {
    date = date.trim()
    let reverse = (`${date}`).split('-')
    reverse = reverse.reverse()
    let dateString = reverse.join(' ')
    return dateString
  }
}

function converZone () {
  let d = new Date()
  let localTime = d.getTime()
  let offset = 4
  let calctime = localTime + (3600000 * offset)
  let nd = new Date(calctime)
  let year = nd.getFullYear()
  let month = nd.getMonth() + 1
  let date = nd.getDate()
  let day = nd.getDay()
  let hours = nd.getHours()
  let minutes = nd.getMinutes()
  hours = hours < 10 ? '0'.concat(hours) : hours
  minutes = minutes < 10 ? '0'.concat(minutes) : minutes
  date = date < 10 ? '0'.concat(date) : date
  month = month < 10 ? '0'.concat(month) : month
  let currentTime = [`${hours} : ${minutes}`, `${days[day]}`, `${date}/${month}/${year}`]
  return currentTime
}
const strFormat = (value) => {
  if (value.length > 4) {
    let str = value.split(' ')
    let strFinal = []
    for (let i = 0; i < str.length; i++) {
      (str[i].split('')).forEach((currentValue) => {
        strFinal.push(currentValue)
      })
    }
    value = ''
    strFinal.forEach((currentValue, index) => {
      if (index % 4 === 0 && index !== 0) {
        value = `${value} ${strFinal[index]}`
      } else {
        value += strFinal[index]
      }
    })
  }
  return value
}
const strSplit = (value) => {
  // let str = value.split(' ')
  // value = ''
  // for (let i = 0; i < str.length; i++) {
  //   value += str[i]
  // }
  const spaceReg = /\s+/g
  return value.replace(spaceReg, '')
}
const defaultValue = (value, type) => {
  switch (type) {
    case 'nationality':
      return value || 'NZ'
    case 'licenseType':
      return value || ''
    default:
      break
  }
  return ''
}
const SelectProps = {
  showSearch: true,
  optionFilterProp: 'children',
  filterOption: (input, option) => {
    return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  },
}
const validateNumber = (rule, value, callback) => {
  if (parseInt(value, 10) < 0) {
    callback('It should be greater than zero')
  }
  callback()
}
const productMention = (title) => {
  return <span style={{ display: 'flex' }}><Input /><Tooltip title="AverageAnnualTurnover"><Icon type="question-circle-o" style={{ margin: '3% 0 0 5px' }} /></Tooltip ></span>
}

/*
* 根据key查找value
*/
const findValueByKey = (dictList, val, keyName) => {
  if (keyName) {
    const data = dictList.filter((item) => {
      return (item[keyName] === val)
    })
    if (data[0]) {
      return data[0].name
    }
  } else {
    const data = dictList.filter((item) => {
      return (item.key === val)
    })
    if (data[0]) {
      return data[0].value
    }
  }
}
/*
* 生成菜单树
*/
const CreateMenuTree = (menuTreeData) => {
  const sortNumber = (a, b) => {
    if (a.bpid === b.bpid) {
      return b.bpid - a.bpid
    }
    return b.bpid - a.bpid
  }
  menuTreeData.sort(sortNumber)
  const treeData = menuTreeData.map((currentData) => {
    return { title: currentData.name, key: currentData.id, parentKey: currentData.bpid }
  })
  for (let i in treeData) {
    for (let j in treeData) {
      if (treeData[i].parentKey === treeData[j].key) {
        if (!treeData[j].children) {
          treeData[j].children = []
        }
        treeData[j].children.push(treeData[i])
        break
      }
    }
  }
  const treeDataResult = treeData.filter((n) => {
    return n.parentKey === 0
  })
  return treeDataResult
}
function keepDecimal (num, bit) {
  const flag = Math.pow(10, bit)
  return Math.floor(num * flag) / flag
}

module.exports = {
  config,
  request,
  color,
  classnames,
  keepDecimal,
  queryURL,
  queryArray,
  arrayToTree,
  converDate,
  converZone,
  strFormat,
  strSplit,
  defaultValue,
  SelectProps,
  validateNumber,
  productMention,
  findValueByKey,
  CreateMenuTree,
}
